package com.woniuxy.opencv.config;

import org.eclipse.paho.client.mqttv3.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

//sk-08192959018e420283fae729af2dcbd9
@Configuration
public class MqttConfig {

    private static final String BROKER_URL = "tcp://120.26.64.89:1883"; // 替换为你的MQTT Broker地址
    private static final String CLIENT_ID = "mqtt-spring-client";
    private static final String USERNAME = "zg"; // 替换为你的用户名
    private static final String PASSWORD = "12345678"; // 替换为你的密码
    private static final String TOPIC_SUBSCRIBE = "woniuSms";
    private static final String TOPIC_PUBLISH = "zhangge";

    private MqttClient mqttClient;
    private final ExecutorService executorService = Executors.newCachedThreadPool();

    @Bean
    public MqttClient mqttClient() throws MqttException {
        mqttClient = new MqttClient(BROKER_URL, CLIENT_ID);
        MqttConnectOptions options = new MqttConnectOptions();
        options.setUserName(USERNAME);
        options.setPassword(PASSWORD.toCharArray());
        options.setCleanSession(true);
        options.setConnectionTimeout(30); // 连接超时设置为30秒
        options.setKeepAliveInterval(120); // 心跳间隔设置为120秒
        connectWithRetry(options);
        setupCallback();
        // 订阅消息
        subscribeTopic(TOPIC_SUBSCRIBE);
        return mqttClient;
    }

    @PostConstruct
    public void init() {
        System.out.println("MQTT client initialized and connected.");

        // 确保 mqttClient 在这里是可用的
        if (mqttClient != null && mqttClient.isConnected()) {
            // 发布消息
            //publishMessage(TOPIC_PUBLISH, "Hello MQTT!");
        } else {
            System.err.println("MQTT Client is not connected.");
        }
    }

    @PreDestroy
    public void close() {
        // 程序关闭时断开连接
        try {
            if (mqttClient != null && mqttClient.isConnected()) {
                mqttClient.disconnect();
                System.out.println("MQTT client disconnected.");
            }
            executorService.shutdown();
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    // 建立连接，带有重试机制
    private void connectWithRetry(MqttConnectOptions options) {
        int retryCount = 0;
        int maxRetries = 5; // 设置最大重试次数
        while (!mqttClient.isConnected() && retryCount < maxRetries) {
            try {
                mqttClient.connect(options);
                System.out.println("Connected to MQTT Broker successfully!");
                retryCount = 0; // 重置重试次数
                break; // 连接成功，退出循环
            } catch (MqttException e) {
                retryCount++;
                System.out.println("Connection failed, retrying... (" + retryCount + "/" + maxRetries + ")");
                try {
                    Thread.sleep(5000 + retryCount * 1000); // 每次重试时增加延时
                } catch (InterruptedException ignored) {
                }
            }
        }
        if (retryCount >= maxRetries) {
            System.err.println("Failed to connect to MQTT Broker after " + maxRetries + " attempts.");
        }
    }

    // 设置回调
    private void setupCallback() {
        mqttClient.setCallback(new MqttCallback() {
            @Override
            public void connectionLost(Throwable cause) {
                System.out.println("Connection lost. Reconnecting...");
                try {
                    connectWithRetry(new MqttConnectOptions());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void messageArrived(String topic, MqttMessage message) {
                System.out.println("Message received from topic " + topic + ": " + new String(message.getPayload()));
                executorService.submit(() -> processMessage(topic, message));
            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken token) {
                System.out.println("Message delivered!");
            }
        });
    }

    // 处理接收到的消息
    private void processMessage(String topic, MqttMessage message) {
        String msg = new String(message.getPayload());
        try {
//            PutBox putBox = JSON.parseObject(msg, PutBox.class);
//            if (StringUtils.isBlank(putBox.getBoxName()) || StringUtils.isBlank(putBox.getPhone())) {
//                return;
//            }
//
//            // 获取空箱子
//            List<Box> boxList = boxService.boxRelease(putBox.getBoxName());
//            if (boxList.isEmpty()) {
//                respondWithNoBox(putBox);
//            } else {
//                handleBoxAvailable(putBox, boxList);
//            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    // 发布消息
    public void publishMessage(String topic, String payload) {
        try {
            if (mqttClient != null && mqttClient.isConnected()) {
                MqttMessage message = new MqttMessage(payload.getBytes());
                message.setQos(1); // 设置QoS级别
                mqttClient.publish(topic, message);
                System.out.println("Message published to topic " + topic + ": " + payload);
            } else {
                System.err.println("MQTT Client is not connected. Cannot publish message.");
            }
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    // 订阅主题
    public void subscribeTopic(String topic) {
        try {
            mqttClient.subscribe(topic, 1); // 设置QoS级别
            System.out.println("Subscribed to topic " + topic);
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

}
